﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;

namespace BoardGamePlayer
{
    /// <summary>
    /// Interaction logic for Dice.xaml
    /// </summary>
    public partial class Dice : ScatterViewItem
    {

        private int currentValue;
        private Random rand;
        private double tumbleDelta = 150.0;
        private double tumbleDistance;
        public Dice()
        {
            InitializeComponent();
            CurrentValue = 1;
            rand = new Random();
        }

        public int CurrentValue 
        {
            get { return currentValue; }
            set 
            { 
                currentValue = value;
                foreach (FrameworkElement element in faceGrid.Children) 
                {
                    if (Int32.Parse((string)element.Tag) == currentValue)
                    {
                        element.Visibility = Visibility.Visible;
                    }
                    else 
                    {
                        element.Visibility = Visibility.Hidden;
                    }
                }
            }
        }

        public void Tumble() 
        {
            int newValue = CurrentValue;
            while (newValue == CurrentValue) 
            {
                newValue = rand.Next(1, 7);
            }
            CurrentValue = newValue;
        }

        protected override void OnManipulationDelta(ManipulationDeltaEventArgs e)
        {
            if (e.IsInertial)
            {
                if (e.DeltaManipulation.Translation.Length + tumbleDistance > tumbleDelta)
                {
                    Tumble();
                    tumbleDistance = 0.0;
                }
                else 
                {
                    tumbleDistance += e.DeltaManipulation.Translation.Length;
                }
            }

            base.OnManipulationDelta(e);
        }

        protected override void OnManipulationStarted(ManipulationStartedEventArgs e)
        {
            BeginDragDrop(this);
            base.OnManipulationStarted(e);
        }
    }
}
